package com.duoduo.nacos.member.controller;

import com.duoduo.common.utils.R;
import com.duoduo.nacos.member.feign.OrderFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @program: duoduo-nacos
 * @description: 用户接口
 * @author: 拾光！
 * @create: 2021-06-20 09:29
 */
@RestController
@RequestMapping("/user")
@Slf4j
@RefreshScope
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderFeignService orderFeignService;
    @Value("${user}")
    String userName;

    @GetMapping("/test")
    public R test(){
        log.info("获取到的姓名：{}",userName);
        return R.ok().put("userName",userName);
    }
    @GetMapping(value = "/findOrderByUserId/{id}")
    public R findOrderByUserId(@PathVariable("id") Integer id) {
        log.info("根据userId:"+id+"查询订单信息");
        // RestTemplate调用
       // String url = "http://localhost:8020/order/findOrderByUserId/"+id;
       // R result = restTemplate.getForObject(url,R.class);

        //模拟ribbon实现
        // String url = getUri("duoduo-order")+"/order/findOrderByUserId/"+id;
        // 添加@LoadBalanced
        // String url = "http://duoduo-order/order/findOrderByUserId/"+id;
        // R result = restTemplate.getForObject(url,R.class);

        //feign调用
        R result = orderFeignService.findOrderByUserId(id);

        return result;
    }
   //  @Autowired
   // private DiscoveryClient discoveryClient;
   // public String getUri(String serviceName) {
   //     List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
   //     if (serviceInstances == null || serviceInstances.isEmpty()) {
   //         return null;
   //     }
   //     int serviceSize = serviceInstances.size();
   //     //轮询
   //     int indexServer = incrementAndGetModulo(serviceSize);
   //     return serviceInstances.get(indexServer).getUri().toString();
   // }
   // private AtomicInteger nextIndex = new AtomicInteger(0);
   // private int incrementAndGetModulo(int modulo) {
   //     for (;;) {
   //         int current = nextIndex.get();
   //         int next = (current + 1) % modulo;
   //         if (nextIndex.compareAndSet(current, next) && current < modulo){
   //             return current;
   //         }
   //     }
   // }
   @PostMapping("/aaa")
   public List<String>  aaa(@RequestBody List<String> aaa){
       for (String s : aaa) {
           System.out.println(s);
       }
       return aaa;
   }

}
